import { createStore, Store, useStore as baseUseStore } from 'vuex'
import type { MutationTree, ActionTree } from 'vuex'
import { InjectionKey } from 'vue'
import { saveLanguageApi } from '@/api/layout'

interface AllStateTypes {
  count: number
  locale: any
  userStatus: number
  roomList: Array<any>
  pageNo: number
  pageSize: number
  total: number
  cityCode: string
  roomDetail: any
  roomId: null
  orderVisible: boolean
}
export const key: InjectionKey<Store<AllStateTypes>> = Symbol('storeKey')

export function useStore() {
  return baseUseStore(key)
}

const state = {
  count: 1,
  locale: null, // 语言包
  userStatus: 0, // 登录态
  roomList: [],
  pageNo: 1,
  pageSize: 6,
  total: 0,
  cityCode: 'hz',
  roomDetail: {},
  roomId: null,
  orderVisible: false
}

const mutations: MutationTree<AllStateTypes> = {
  setCount(state, payload) {
    state.count += payload
    return state.count
  },
  setLanguage(state, payload) {
    state.locale = payload
    return state.locale
  },
  setUserStatus(state, payload) {
    state.userStatus = payload
    return state.userStatus
  }
}
const actions: ActionTree<AllStateTypes, AllStateTypes> = {
  fetchCount({ commit }, payload) {
    setTimeout(() => {
      commit('setCount', payload)
    }, 300)
  },
  async saveLanguage({ commit }, language) {
    const { success } = await saveLanguageApi(language.name)
    if (success) {
      commit('setLanguage', language)
    }
  }
}
export const store = createStore<AllStateTypes>({
  state,
  mutations,
  actions
})
